<template>
  <section class="f-meal-add w-card">
    <div class="title-box">
      <span class="title-text">{{ isEdit? '编辑': '新增'}}商品</span>
      <div v-if="!isEdit">
        <el-button type="primary" @click="submitHandle('add')">确定创建商品</el-button>
      </div>
      <div v-else>
        <el-button @click="cancelEdit()">取消编辑</el-button>
        <el-button type="primary" @click="submitHandle('modify')">确定重新发布商品</el-button>
      </div>
    </div>

    <section class="f-content">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <div class="f-title">基础信息</div>
        <el-row class="f-mt-20">
          <el-col :span="5">
            <el-form-item label="商品名称:" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="起始价格(元):" prop="startPrice">
              <el-input v-model="ruleForm.startPrice" placeholder="请输入起始价格" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="最高价格(元):" prop="maxPrice">
              <el-input v-model="ruleForm.maxPrice" placeholder="请输入最高价格" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="限制年限:" prop="limitYears">
              <el-input v-model="ruleForm.limitYears" placeholder="请输入限制年限" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="商品标题:" prop="title">
              <el-input v-model="ruleForm.title" placeholder="请输入商品标题" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="商品状态:" prop="status">
              <el-select v-model="ruleForm.status" placeholder="请选择商品状态">
                <el-option label="下架" :value="0" />
                <el-option label="上架" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="商品标签:">
              <el-tag style="margin-right: 10px;" v-for="tag in ruleForm.tags" :key="tag" closable :disable-transitions="false"
                size="large" @close="handleClose(tag)">
                {{ tag }}
              </el-tag>
              <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm" />
              <el-button v-else @click="showInput">
                + 新增标签
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="列表展示小图:" prop="smallImage">
              <el-upload class="f-img-uploader" :action="uploadForm.action" :headers="uploadForm.headers" :data="uploadForm.data"
                :show-file-list="false" :on-success="uploadSuccess">
                <img v-if="ruleForm.smallImage" :src="ruleForm.smallImage" class="f-img" />
                <el-icon v-else class="f-img-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="详情展示大图:" prop="largeImage">
              <el-upload class="f-img-uploader" :action="uploadForm.action" :headers="uploadForm.headers" :data="uploadForm.data"
                :show-file-list="false" :on-success="uploadSuccess1">
                <img v-if="ruleForm.largeImage" :src="ruleForm.largeImage" class="f-img1" />
                <el-icon v-else class="f-img-uploader-icon1">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="f-title" style="margin-top:50px">分佣规则</div>
        <el-row class="f-mt-20">
          <el-col :span="7">
            <el-form-item label="用户自主投保佣金规则:" prop="userSelfInsureCommissionStrategyId">
              <el-select v-model="ruleForm.userSelfInsureCommissionStrategyId" placeholder="请选择佣金规则">
                <el-option v-for="(item,index) in incomeRuleList" :key="index" :label="item.strategyName"
                  :value="item.strategyId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="员工代客投保佣金规则:" prop="employeeAssistInsureCommissionStrategyId">
              <el-select v-model="ruleForm.employeeAssistInsureCommissionStrategyId" placeholder="请选择佣金规则">
                <el-option v-for="(item,index) in incomeRuleList" :key="index" :label="item.strategyName"
                  :value="item.strategyId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="用户分享投保佣金规则:" prop="userByOwnerShareCommissionStrategyId">
              <el-select v-model="ruleForm.userByOwnerShareCommissionStrategyId" placeholder="请选择佣金规则">
                <el-option v-for="(item,index) in incomeRuleList" :key="index" :label="item.strategyName"
                  :value="item.strategyId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="f-title" style="margin-top:50px">投保信息</div>
        <el-row class="f-mt-20">
          <el-col :span="5">
            <el-form-item label="发票价范围:" prop="invoicePriceRange">
              <el-input v-model="insuranceRequirement.invoicePriceRange" placeholder="请输入发票价范围" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="公里数限制:" prop="mileageLimit">
              <el-input v-model="insuranceRequirement.mileageLimit" placeholder="请输入公里数限制" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="服务年限:" prop="serviceYears">
              <el-input v-model="insuranceRequirement.serviceYears" placeholder="请输入服务年限" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="车龄限制:" prop="vehicleAgeLimit">
              <el-input v-model="insuranceRequirement.vehicleAgeLimit" placeholder="请输入车龄限制" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="车型要求:" prop="vehicleModelRequirement">
              <el-input v-model="insuranceRequirement.vehicleModelRequirement" placeholder="请输入车型要求" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="质保期要求:" prop="warrantyRequirement">
              <el-input v-model="insuranceRequirement.warrantyRequirement" placeholder="请输入质保期要求" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="车主类型:" prop="ownerTypes">
              <el-select v-model="insuranceRequirement.ownerTypes" placeholder="请选择车主类型" multiple>
                <el-option v-for="(item,index) in ownerTypes" :key="index" :label="item.description" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="车辆性质:" prop="vehicleNatures">
              <el-select v-model="insuranceRequirement.vehicleNatures" placeholder="请选择车辆性质" multiple>
                <el-option v-for="(item,index) in vehicleNatures" :key="index" :label="item.description" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="f-title f-mb-20" style="margin-top:50px">
          <span>保费计算</span>
          <el-button plain type="primary" @click="handlePremiumCalculations('add')">+ 新增</el-button>
        </div>
        <el-row v-for="(item,index) in premiumCalculations" :key="index">
          <el-col :span="5">
            <el-form-item label="服务年限:" prop="serviceYears">
              <el-input v-model="item.serviceYears" placeholder="请输入服务年限" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="保费比例:" prop="premiumRate">
              <el-input v-model="item.premiumRate" placeholder="请输入保费比例">
                <template #append>
                  <p style="padding:0 20px">‱</p>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <el-form-item label="固定其他费用:" prop="fixedFee">
              <el-input v-model="item.fixedFee" placeholder="请输入固定其他费用">
                <template #append>
                  <p style="padding:0 20px">分</p>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :offset="6" :span="1" v-if="premiumCalculations.length >= 2">
            <el-button style="margin-top: 32px;" type="danger" @click="handlePremiumCalculations(index)">- 删除</el-button>
          </el-col>
        </el-row>

        <div class="f-title" style="margin-top:50px">
          <span>富文本</span>
          <el-button plain type="primary" @click="handleRichTexts('add')">+ 新增</el-button>
        </div>
        <el-row v-for="(item,index) in richTexts" :key="index">
          <el-col :span="5">
            <el-form-item label="富文本类型:" prop="contentType">
              <el-select v-model="item.contentType" placeholder="请选择富文本内容">
                <el-option label="保障内容" :value="1" />
                <el-option label="权益内容" :value="2" />
                <el-option label="使用说明" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="16">
            <el-form-item label="富文本详情:" prop="content">
              <Editor width="100%" v-model="item.content" :api-key="apiKey" :init="init" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="1" v-if="richTexts.length >= 2">
            <el-button style="margin-top: 32px;" type="danger" @click="handleRichTexts(index)">- 删除</el-button>
          </el-col>
        </el-row>
      </el-form>
    </section>
  </section>
</template>

<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStateStore } from '@/store'
import api from './api.js'
import Editor from "@tinymce/tinymce-vue";
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad, getStore, errorDeal } from '@/utils/utils'
import axios from "axios"

export default {
  components: {
    Editor,
  },

  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: {}
    }
  },

  emits: ["cancelEdit", "setModify"],

  setup(props, context) {
    const store = useStateStore()

    const router = useRouter()
    const route = useRoute();

    const ruleFormRef = ref(null)
    const InputRef = ref();

    const state = reactive({
      ruleForm: {
        tags: []
      },
      rules: {
        name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
      },

      uploadForm: {
        action: '/ums/file/upload/img',
        headers: {
          Authorization: getStore('USER_AUTHOR_INRE').Authorization || `'','','',3,20,''`,
          Token: `Bearer ${window.localStorage.getItem("USER_TOKEN_INRE")}`,
          platformHeadType: 'rcmsPlatform'
        },
        data: {}
      },

      incomeRuleList: [],
      inputValue: '',
      inputVisible: false,

      ownerTypes: [],
      vehicleNatures: [],

      insuranceRequirement: {},
      premiumCalculations: [{}],
      richTexts: [{}],
    })

    onMounted(() => {
      if (props.isEdit) {
        state.ruleForm = JSON.parse(JSON.stringify(props.formData))
        state.ruleForm.maxPrice = state.ruleForm.maxPrice / 100
        state.ruleForm.startPrice = state.ruleForm.startPrice / 100
        state.insuranceRequirement = state.ruleForm.insuranceRequirement
        state.premiumCalculations = state.ruleForm.premiumCalculations
        state.richTexts = state.ruleForm.richTexts
        state.ruleForm.scenarioCommissionStrategies.forEach(item => {
          if (item.sceneType == 1) {
            state.ruleForm.userSelfInsureCommissionStrategyId = item?.commissionStrategy?.strategyId
          } else if (item.sceneType == 2) {
            state.ruleForm.employeeAssistInsureCommissionStrategyId = item?.commissionStrategy?.strategyId
          } else if (item.sceneType == 3) {
            state.ruleForm.userByOwnerShareCommissionStrategyId = item?.commissionStrategy?.strategyId
          }
        })

        let tags = []
        state.ruleForm.tags.forEach(item => {
          tags.push(item.tagName)
        })
        state.ruleForm.tags = tags
      }

      getIncomeRuleList()
      getOwnerType()
      getVehicleNature()
    })

    const getIncomeRuleList = () => {
      let json = {}
      api.incomeRuleAll(json).then(res => {
        state.incomeRuleList = res.data.list
      })
    }

    const getOwnerType = () => {
      api.ownerType().then(res => {
        state.ownerTypes = res.data
      })
    }

    const getVehicleNature = () => {
      api.vehicleNature().then(res => {
        state.vehicleNatures = res.data
      })
    }

    function submitHandle(type) {
      ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          let json = JSON.parse(JSON.stringify(state.ruleForm))
          let insuranceRequirement = JSON.parse(JSON.stringify(state.insuranceRequirement))
          let premiumCalculations = JSON.parse(JSON.stringify(state.premiumCalculations))
          let richTexts = JSON.parse(JSON.stringify(state.richTexts))

          json.startPrice = json.startPrice * 100
          json.maxPrice = json.maxPrice * 100

          json.insuranceRequirement = insuranceRequirement
          json.premiumCalculations = premiumCalculations
          json.richTexts = richTexts

          console.log(json)

          if (type == 'add') {
            api.goodsCreate(json).then(res => {
              successDeal('新增成功！')
              setTimeout(() => {
                router.go(-1)
              }, 500)
            })
          } else if (type == 'modify') {
            api.goodsModify(json).then(res => {
              successDeal('编辑成功！')
              context.emit('setModify')
            })
          }
        }
      })
    }

    const cancelEdit = () => {
      context.emit('cancelEdit')
    }

    const uploadSuccess = (res) => {
      if (res.code == '200') {
        state.ruleForm.smallImage = res.data.ossUrl
        ruleFormRef.value.validate()
      } else {
        errorDeal(res.msg)
      }
    }

    const uploadSuccess1 = (res) => {
      if (res.code == '200') {
        state.ruleForm.largeImage = res.data.ossUrl
        ruleFormRef.value.validate()
      } else {
        errorDeal(res.msg)
      }
    }

    const handleClose = (tag) => {
      state.ruleForm.tags.splice(state.ruleForm.tags.indexOf(tag), 1)
    }

    const showInput = () => {
      state.inputVisible = true
    }

    const handleInputConfirm = () => {
      if (state.inputValue) {
        state.ruleForm.tags.push(state.inputValue)
      }
      state.inputVisible = false
      state.inputValue = ''
    }

    const handlePremiumCalculations = (type) => {
      if (type == 'add') {
        state.premiumCalculations.push({})
      } else {
        state.premiumCalculations.splice(type, 1)
      }
    }

    const handleRichTexts = (type) => {
      if (type == 'add') {
        state.richTexts.push({})
      } else {
        state.richTexts.splice(type, 1)
      }
    }

    const tiny = reactive(
      {
        content: '',
        apiKey: "z7jl7oc1dai5wa9sbda1f2xktysqj3d2hiooprp5f1u6pabp", //线网
        init: {
          language: "zh_CN",
          placeholder: "在这里输入文字",
          min_width: 320,
          min_height: 220,
          height: 500,
          resize: "both",
          branding: false,

          font_formats:
            "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;", //字体样式
          plugins:
            "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave emoticons", //插件配置 axupimgs indent2em
          toolbar: [
            "fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | bullist numlist | blockquote subscript superscript removeformat ",
            "styleselect formatselect fontselect fontsizeselect |  table image axupimgs media emoticons charmap hr pagebreak insertdatetime  selectall visualblocks searchreplace | code print preview | indent2em lineheight formatpainter",
          ],
          images_upload_url: '/ums/file/upload/img',
          paste_data_images: false,
          images_upload_handler: (blobInfo, success, failure) => {
            const myBlob = blobInfo.blob()
            let param = new FormData()
            param.append('file', myBlob, Math.random() * 1000000 + 1 + '.jpg')
            const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
            const uesrInfo = getStore("USER_INFO_INRE") || {};
            const Authorization = getStore("USER_AUTHOR_INRE") || {
              Authorization: `'','','',3,20,''`,
            };
            let config = {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: token ? `Bearer ${token}` : '',
                username: uesrInfo.username || '',
                Authorization: Authorization.Authorization,
                platformHeadType: 'rcmsPlatform',
              }
            }
            axios.post('/ums/file/upload/img', param, config).then(res => {
              if (res.data.code == '200') {
                success(res.data.data.ossUrl)
              } else {
                warningDeal(res.data.msg)
              }
            }).catch(err => {
              console.log(err)
            })
          },

          file_picker_types: "file image media",
          // 文件上传处理函数
          file_picker_callback: function (callback, value, meta) {
            let filetype;
            if (meta.filetype == "image") {
              filetype = ".jpg, .jpeg, .png, .gif, .ico, .svg";
            } else if (meta.filetype == "media") {
              filetype = ".mp3, .mp4, .avi, .mov";
            } else {
              filetype =
                ".pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4, .jpg, .jpeg, .png, .gif, .ico, .svg";
            }
            let inputElem = document.createElement("input")
            inputElem.setAttribute("type", "file")
            inputElem.setAttribute("accept", filetype)
            inputElem.click()
            inputElem.onchange = () => {
              state.loading = true
              let file = inputElem.files[0];
              let param = new FormData()
              param.append('file', file, file.name)
              const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
              const uesrInfo = getStore("USER_INFO_INRE") || {};
              const Authorization = getStore("USER_AUTHOR_INRE") || {
                Authorization: `'','','',3,20,''`,
              };
              let config = {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  token: token ? `Bearer ${token}` : '',
                  username: uesrInfo.username || '',
                  Authorization: Authorization.Authorization,
                  platformHeadType: 'rcmsPlatform',
                }
              }
              axios.post('/ums/file/upload/img', param, config).then(res => {
                if (res.data.code == '200') {
                  callback(res.data.data.ossUrl, { title: file.name })
                } else {
                  warningDeal(res.data.msg)
                }
                state.loading = false
              }).catch(err => {
                console.log(err)
                state.loading = false
              })
            }
          },
        },
      }
    )

    return {
      ...toRefs(state),
      ...toRefs(tiny),
      ruleFormRef,
      submitHandle,
      cancelEdit,
      uploadSuccess,
      uploadSuccess1,
      showInput,
      handleClose,
      handleInputConfirm,
      handlePremiumCalculations,
      handleRichTexts,
    }
  }
}
</script>

<style lang='scss' scoped>
.f-meal-add {
  box-sizing: border-box;
  padding: 20px;
  height: 100%;
  > .title-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30px;
    > .title-text {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .f-content {
    padding-left: 5px;
    .f-title {
      font-weight: bold;
      font-size: 15px;
      color: #000000;
      border-bottom: 1px solid #eaeaea;
      padding-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .f-tips {
        color: #f73e3e;
        font-size: 12px;
        font-weight: 500;
        margin-left: 40px;
      }
    }
    .f-tabel {
      border: 1px solid #acacac;
      width: 800px;
    }
    .f-guige-box {
      font-size: 14px;
      color: #404040;
      background: #eef2f4;
      display: flex;
      align-items: center;
      padding: 16px 10px;
      margin-top: 20px;
    }
  }
  .f-divider {
    height: 1px;
    border-top: 1px dashed #aaaaaa;
    margin: 32px 0 27px 0;
  }
}
</style>

<style>
.f-img-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.f-img-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.f-img-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 125px;
  height: 125px;
  text-align: center;
}
.f-img {
  width: 125px;
  height: 125px;
}

.el-icon.f-img-uploader-icon1 {
  font-size: 28px;
  color: #8c939d;
  width: 275px;
  height: 125px;
  text-align: center;
}
.f-img1 {
  width: 175px;
  height: 125px;
}
</style>